<template>
    <div>
      <el-form :model="postForm" :rules="rules" ref="postForm" class="form">
        <el-col :span="12" :offset="5">
          <el-form-item class="formTop">
            <h2>编辑院校资料</h2>
          </el-form-item>
          <el-form-item label="院校名称" label-width="80px" prop="academyName">
            <el-input v-model="postForm.academyName"></el-input>
          </el-form-item>
          <el-form-item label="校标/背景" label-width="80px">
            <el-col :span="12">
            <el-upload
              style="margin-left:10px"
              :headers="headers"
              action="/tools/oss/upload"
              :on-preview="handlePreview"
              :before-remove="beforeRemove_icon"
              :on-remove="handleRemove_icon"
              :on-success="handleUploadSuccess_icon"
              list-type="picture"
                :file-list="fileList_icon"
              :limit="1">
              <el-button size="small" type="primary">上传校标</el-button> <span>（建议上传尺寸 200 * 200）</span>
            </el-upload>
            </el-col>
            <el-col :span="12">
            <el-upload
              style="margin-left:10px"
              :headers="headers"
              action="/tools/oss/upload"
              :on-preview="handlePreview"
              :before-remove="beforeRemove_image"
              :on-remove="handleRemove_image"
              :on-success="handleUploadSuccess_image"
              list-type="picture"
                :file-list="fileList_image"
              :limit="1">
              <el-button size="small" type="primary">上传背景</el-button><span>（建议上传尺寸 750 * 380）</span>
            </el-upload>
            </el-col>            
          </el-form-item>
          <el-form-item label="院校性质" label-width="80px" prop="academyAttr">
            <el-input v-model="postForm.academyAttr"></el-input>
          </el-form-item>
          <el-form-item label="院校类型" label-width="80px" prop="academyLevel">
            <el-input v-model="postForm.academyLevel"></el-input>
          </el-form-item>
          <el-form-item label="院校特色" label-width="80px" prop="academyLevel">
            <el-input v-model="postForm.feature"></el-input>
          </el-form-item>
          <el-form-item label="院校地址" label-width="80px" prop="academyLevel">
            <el-input v-model="postForm.address"></el-input>
          </el-form-item>
          <el-form-item label="院校网站" label-width="80px" prop="website">
            <el-input v-model="postForm.website"></el-input>
          </el-form-item>
          <el-form-item label="院校代码" label-width="80px" prop="academyCode" :rules="[{required: true, message: '请输入院校代码', trigger: 'change'},{validator: checkAcademyCode, trigger: 'change'}]">
            <el-input v-model.number="postForm.academyCode" placeholder="请输入6位数字"></el-input>
          </el-form-item>
          <el-form-item label="国标码" label-width="80px" prop="nationalCode" :rules="[{required: true, message: '请输入国标码', trigger: 'change'},{validator: checkNationalCode, trigger: 'change'}]">
            <el-input v-model.number="postForm.nationalCode" placeholder="请输入5位数字"></el-input>
          </el-form-item>
          <el-form-item label="院校电话" label-width="80px" prop="telephone">
            <el-input v-model="postForm.telephone"></el-input>
          </el-form-item>
          <el-form-item label="所属省市" label-width="80px" :rules="[{required: true}]">
            <el-cascader change-on-select  clearable placeholder="请选择所属省市" expand-trigger="click" :options="areaCascadeOptionss" v-model="areaOption" />
            <span class="hint">&nbsp;&nbsp;&nbsp;学校所属省市必须选择到 市级</span>
          </el-form-item>
          <el-form-item label="院校介绍" label-width="80px">
            <Tinymce :height=400 ref="editor" v-model="postForm.introduction"/>
          </el-form-item>
          <el-form-item label="招生简章" label-width="80px">
            <Tinymce :height=400 ref="editor" v-model="postForm.catalog"/>
          </el-form-item>
          <el-form-item class="updateBtn">
            <el-button @click="handleClose" type="info" plain >取 消</el-button>
            <el-button type="primary" @click="updateForm">保 存</el-button>
          </el-form-item>
        </el-col>  
      </el-form>
    </div>
</template>

<script>
import { mapActions, mapGetters } from 'vuex'
import { getAreaCascadeSupply, getArea, add } from '@/api/academy'
import { getToken } from '@/utils/auth' // 验权
import Tinymce from '@/components/Tinymce'
import { validateURL } from '@/utils/validate'

export default {
  name: 'add',
  components: { Tinymce },
  props: {

  },
  data() {
    return {
      headers:{},
      areaOption: [],
      areaCascadeOptionss:[],
      fileList_icon:[],
      fileList_image:[],
      postForm: {
        academyName: '',
        academyCode: '',
        nationalCode: '',
        icon: '',
        image: '',
        academyAttr: '',
        academyLevel: '',
        feature: '',
        academyName: '',
        address: '',
        website: '',
        telephone: '',
        introduction: '',
        catalog: '',
        city: '',
        province: '',
        createTime: new Date().getTime()
      },
      rules: {
        academyName:  [{ required: true, message: '请输入院校名称', trigger: 'change' }],
        telephone:  [{ required: true, message: '请输入院校电话', trigger: 'change' }]
      }
    }
  },
  computed: {

  },
  created() {

  },
  mounted() {
    this.getAreaCascadeSupply()
    this.headers = { accessToken:getToken() }
  },
  watch: {
    areaOption(e){
      // console.log(e)
    }
  },
  methods: {
  // 验证院校代码和国标码必须为数字
    checkAcademyCode(rules, value, callback){
      if (!value) {
        return callback(new Error('院校代码不能为空'))
      }
      setTimeout(() => {
        if (!Number.isInteger(value)) {
          callback(new Error('请输入数字值'))
        } else {
          if (value.toString().length != 6) {
            callback(new Error('必须为六位数'))
          } else {
            callback()
          }
        }
      }, 1000)
    },
    checkNationalCode(rules, value, callback){
      if (!value) {
        return callback(new Error('国标码不能为空'))
      }
      setTimeout(() => {
        if (!Number.isInteger(value)) {
          callback(new Error('请输入数字值'))
        } else {
          if (value.toString().length != 5) {
            callback(new Error('必须为五位数'))
          } else {
            callback()
          }
        }
      }, 1000)
    },
    //上传校标/背景
    handleUploadSuccess_icon(rst){
      const { code, data:{ picUrlList } } = rst
      if(code == 0){
        this.postForm['icon'] = picUrlList[0]
      }
    },
    handleUploadSuccess_image(rst){
      const { code, data:{ picUrlList } } = rst
      if(code == 0){
        this.postForm.image = picUrlList[0]
      }
    },
    handlePreview(file) {
    },
    beforeRemove_icon(file, fileList) {
      return this.$confirm(`此操作将永久删除该图片, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
    },
    handleRemove_icon(file, fileList_icon){
      this.postForm.icon = ''
    },
    beforeRemove_image(file, fileList) {
      return this.$confirm(`此操作将永久删除该图片, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
    },
    handleRemove_image(file, fileList_image) {
      this.postForm.image = ''
    },
    // 获得完整的区域级联,但是要删除 区/县/镇
    getAreaCascadeSupply(){
      getAreaCascadeSupply().then(res => {
        if(res.code == 0){
          res.data.forEach(item => {
            if(item.children){
              item.children.forEach(i => {
                delete i.children
              })
            }
          })
          this.areaCascadeOptionss = res.data
        }
      }).catch(err => {})
    },
    // 映射 Actions
    ...mapActions(['GetAreaCascadeOptions']),
    updateForm(){
      if(this.postForm.academyName.trim().length == 0 || this.postForm.academyCode.length == 0 || this.postForm.nationalCode.length == 0 || this.postForm.telephone.length == 0){
        this.$message({
          title: '失败',
          message: '带 * 号项为必填项，请输入后再保存',
          type: 'error',
          duration: 2000
        })
        return
      }
      if(this.postForm.academyName.trim().length == 0){
        this.$message({
          title: '失败',
          message: '请输入院校名称',
          type: 'error',
          duration: 2000
        })
        return
      }
      if(this.areaOption.length != 2){
        this.$message({
          title: '失败',
          message: '学校所属省市必须选择到 市级',
          type: 'error',
          duration: 2000
        })
        return
      }
      const areaId = { id : this.areaOption[this.areaOption.length - 1] }
      getArea(areaId).then(res => {
        if(res.code == 0){
          if(res.data.fatherLabel){
            this.postForm.province = res.data.fatherLabel
            this.postForm.city = res.data.label
          }else{
            this.postForm.province = res.data.label
            this.postForm.city = ''
          }
        }
        const params = this.postForm
        params['buffer'] = ''
        params['combined'] = null
        params['details'] = ''
        params['followCount'] = null
        params['identifier'] = null
        params['isDelete'] = 0
        params['principle'] = ''
        params['recommend'] = null
        params['updateTime'] = ''
        params['video'] = ''
        params['principle'] = ''
        add(params).then(res => {
          if (res.code == 0) {
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
            this.$router.push({ path:'./list' })
          }else{
            this.$message({
              title: '失败',
              message: message,
              type: 'error',
              duration: 2000
            })
          }
        }).catch(() => {})
      }).catch(() => {})
    },
    handleClose() {
      this.$confirm('数据未保存，确认清空内容？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$refs.postForm.resetFields()
      }).catch(() => {})
    }
  }
}
</script>

<style scoped lang="scss">
.form{
  margin-top: 50px;
}
.hint{
  font-size: 12px;
  color: #999999;
}
.formTop{
  width: 300px;
  margin: 0 auto 20px;
}
.updateBtn{
  width: 300px;
  margin: 50px auto 80px;
}
</style>
